package jym.tan.movielibrary.component.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;

import jym.tan.movielibrary.component.ui.table.model.MovieSearchResultTableModel;
import jym.tan.movielibrary.constant.ComponentConstant;
import jym.tan.movielibrary.dto.MovieSearch;
import jym.tan.movielibrary.factory.ComponentFactory;
import jym.tan.movielibrary.factory.ModelFactory;
import jym.tan.movielibrary.model.MovieSearchModel;
import jym.tan.movielibrary.tmdb.Movie;
import jym.tan.movielibrary.utils.ComponentUtils;
import jym.tan.movielibrary.utils.ModelUtils;

public class MovieTitleConfirmListener implements ActionListener {

	public void actionPerformed(ActionEvent actionEvent) {
		if (actionEvent.getSource() == ComponentFactory.getMovieTitleConfirmButton()) {
			String movieTitle = ComponentFactory.getMovieTitleTextField().getText();
			Object object = getMovieSearchResults(movieTitle);
			validateResult(object);
		}
	}

	private Object getMovieSearchResults(String name) {
		return Movie.Search.getInstance().getMovieSearchResult(name);
	}

	private void validateResult(Object object) {
		ComponentFactory.getMovieTitleConfirmDialog().dispose();
		if (object == null) {
			ComponentUtils.showErrorMessage(ComponentFactory.getMovieTitleConfirmDialog(), ComponentConstant.Message.ERROR_OCCURED);
		} else if (object instanceof Integer) {
			ComponentUtils.showWarningMessage(ComponentFactory.getMovieTitleConfirmDialog(), ComponentConstant.Message.MOVIE_NOT_FOUND);
		} else {
			MovieSearch[] movieSearchResults = (MovieSearch[]) object;
			processMovieSearchResults(Arrays.asList(movieSearchResults));
		}
	}

	private void processMovieSearchResults(List<MovieSearch> movieSearchResults) {		
		List<MovieSearchModel> movieSearchModels = ModelUtils.getMovieSearchModels(movieSearchResults);
		MovieSearchResultTableModel movieSearchResultTableModel = (MovieSearchResultTableModel) ModelFactory.getMovieSearchResultTableModel();
		movieSearchResultTableModel.setMovieSearchModels(movieSearchModels);
		movieSearchResultTableModel.fireTableDataChanged();
	}
}
